package com.guanyua.eims.common.filter;

import com.guanyua.eims.common.util.JsonUtil;
import com.guanyua.eims.common.util.RequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 请求日志拦截器
 */
@Configuration
@WebFilter(filterName ="requestLogFilter", urlPatterns = "/*")
@Order(value = 1)
@Slf4j
public class LogFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        log.debug("过滤器-日志-初始化");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        String contentType = request.getContentType();
        RequestWrapper requestWrapper = null;
        HttpServletResponse response = (HttpServletResponse) res;

        //**********************************请求日志
        log.info("");
        log.info("***************请求信息开始***************");
        log.info("URL: " + request.getRequestURL());
        log.info("METHOD: " + request.getMethod());
        log.info("CONTENT_TYPE: " + contentType);
        log.info("TOKEN: " + request.getHeader("token"));
        if(request.getMethod().equals("GET") || contentType == null || contentType.contains("application/x-www-form-urlencoded")){
            log.info("PARAMES: " + JsonUtil.objectToJson(request.getParameterMap()));
        } else if(contentType.contains("multipart/form-data") || contentType.contains("application/json") || contentType.contains("xml")){
            requestWrapper = new RequestWrapper(request);
            try {
                BufferedReader streamReader = new BufferedReader( new InputStreamReader(requestWrapper.getInputStream(), "UTF-8"));
                StringBuilder responseStrBuilder = new StringBuilder();
                String inputStr;
                while ((inputStr = streamReader.readLine()) != null){
                    responseStrBuilder.append(inputStr);
                }

                log.info("PARAMES: " + responseStrBuilder.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("***************请求信息结束***************");
        log.info("");

        chain.doFilter(requestWrapper == null ? request : requestWrapper, response);
    }

    @Override
    public void destroy() {
        log.debug("过滤器-日志-销毁");
    }

}